@file:Suppress("DEPRECATION")

package com.jerry.usbserial.util.task.udp

import android.app.AlertDialog
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.os.AsyncTask
import com.espressif.iot.esptouch.EsptouchTask
import com.espressif.iot.esptouch.IEsptouchResult
import com.espressif.iot.esptouch.IEsptouchTask
import com.jerry.usbserial.util.showToast
import com.jerry.usbserial.util.to4HByteArray

/**
 * Created by dugang on 2020/7/6.
 */
class SmartConnectTask(private val mContext: Context, private val onCompleted: (() -> Unit)) :
    AsyncTask<ByteArray, IEsptouchResult, List<IEsptouchResult>>() {

    private var mProcessDialog: ProgressDialog? = null
    private var mResultDialog: AlertDialog? = null
    private var mIEsptouchTask: IEsptouchTask? = null
    private val mLock = Any()

    fun cancelEsptouch() {
        cancel(true)
        mProcessDialog?.dismiss()
        mResultDialog?.dismiss()
        mIEsptouchTask?.interrupt()
    }

    override fun onPreExecute() {
        mProcessDialog = ProgressDialog(mContext).apply {
            setMessage("正在执行配网, 请稍候...")
            setCanceledOnTouchOutside(false)
            setCancelable(false)
            setButton(Dialog.BUTTON_NEGATIVE, context.getString(android.R.string.cancel)) { _, _ ->
                synchronized(mLock) {
                    mIEsptouchTask?.interrupt()
                }
            }
            setOnCancelListener {
                synchronized(mLock) {
                    mIEsptouchTask?.interrupt()
                }
            }
            show()
        }
    }


    override fun onProgressUpdate(vararg values: IEsptouchResult?) {
        values[0]?.let {
            mContext.showToast(" ${it.bssid}已连接到 WIFI")
        }
    }


    override fun doInBackground(vararg params: ByteArray): List<IEsptouchResult> {
        var taskResultCount: Int
        synchronized(mLock) {
            val ssid: ByteArray = params[0]
            val bssid: ByteArray = params[1]
            val password: ByteArray = params[2]
            val deviceCountData: ByteArray = params[3]
            val broadcastData: ByteArray = params[4]
            taskResultCount = Integer.parseInt(String(deviceCountData), 16)
            mIEsptouchTask = EsptouchTask(ssid, bssid, password, mContext).apply {
                setPackageBroadcast(broadcastData.contentEquals(1.to4HByteArray()))
                setEsptouchListener { values: IEsptouchResult? -> publishProgress(values) }
            }
        }
        return mIEsptouchTask!!.executeForResults(taskResultCount)
    }

    override fun onPostExecute(result: List<IEsptouchResult>?) {
        mProcessDialog?.dismiss()
        if (result == null) {
            mResultDialog = AlertDialog.Builder(mContext)
                .setTitle("错误")
                .setMessage("建立 EspTouch 任务失败, 端口可能被其他程序占用")
                .setCancelable(false)
                .setPositiveButton("确定", null)
                .show()
            return
        }

        if (result[0].isCancelled) return
        if (!result[0].isSuc) {
            mResultDialog = AlertDialog.Builder(mContext)
                .setTitle("错误")
                .setMessage("无法识别设备,请重试!")
                .setCancelable(false)
                .setPositiveButton("确定", null)
                .show()
            return
        }
        val messageList = mutableListOf<String>()
        result.forEach {
            messageList.add("BSSID: ${it.bssid}, 地址: ${it.inetAddress.hostAddress}")
        }
        mResultDialog = AlertDialog.Builder(mContext)
            .setTitle("配网完成")
            .setItems(messageList.toTypedArray(), null)
            .setPositiveButton(android.R.string.ok, null)
            .show()
        onCompleted.invoke()
    }
}